<template>
	<div id="metaColumeManager">
		<v-header title="用户管理" :showDownloadBtn="isDownLoadShow" :saveShow="false"></v-header>
    <div class="meta-colume-box">
      <el-container>
        <el-header class="header-tool-bar" height="50px">
          <!-- 工具栏 -->
          <el-row>
            <el-button type="primary" size="mini" @click="addMetaColume">增加</el-button>
            <el-button type="primary" size="mini" @click="deleteMetaColume">删除</el-button>
            <!-- <el-button type="primary" size="mini" @click="modifyMetaColume">编辑</el-button>
            <el-button type="primary" size="mini" @click="refresh">刷新</el-button> -->
            <!-- <span class="conditionquery">
              <el-input v-model="condition" size="mini" prefix-icon="el-icon-search" placeholder="请输入内容"
                          clearable></el-input>
              <el-button type="primary" size="mini" @click="conditionquery">查询</el-button>
            </span> -->
          </el-row>
        </el-header>
        <el-main class="main-cont">
          <!-- 表格 -->
          <el-table :data="metaColumeList" @selection-change="handleSelectionChange" v-loading="tableLoading"
          @select="handleSelect" @select-all="handleSelect" v-model="checked" ref="table" class="meta-col-table">
              <el-table-column type="selection" width="auto"></el-table-column>
              <el-table-column prop="name" label="姓名" width="auto"></el-table-column>
              <!-- <el-table-column prop="app_id" label="app_id" width="auto"></el-table-column> -->
              <el-table-column prop="code" label="登录名" width="auto"></el-table-column>
                          <el-table-column prop="code" label="管理员" width="auto">
                              <template slot-scope="scope">
                                  <span>{{scope.row.is_admin==='1'?'是':'否'}}</span>
                              </template>
                          </el-table-column>
              <el-table-column prop="assign" label="分配" width="auto">
                              <template slot-scope="scope">
                                  <el-button @click="handleClick(scope.row)" type="text" size="mini">分配菜单</el-button>
                              </template>
                          </el-table-column>
              <!-- <el-table-column prop="colume_chs" label="中文字段名" width="auto"></el-table-column>
              <el-table-column prop="colume_attr" label="字段属性" width="auto" :formatter="fmtcolumeattr"></el-table-column>
              <el-table-column prop="code_id" label="代码ID" width="auto"></el-table-column> -->
          </el-table>
          <!-- 分页 -->
          <!--<el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="pageTotal">
          </el-pagination>-->
        </el-main>
      </el-container>
    </div>
		<!-- 新增/编辑弹窗 -->
		<el-dialog :title="editMode == 'ADD' ? '新增用户':'编辑用户'" :visible.sync="editDialogShow" width="600px" v-model="editMode" @close="closeDialog">
				<el-form :model="metaColumeForm" :rules="rules" ref="metaColumeForm" label-width="140px">
						<el-row :gutter="24">
								<el-col :span="18" :offset="2">
										<el-form-item label="姓名" prop="name">
												<el-input v-model="metaColumeForm.name"/>
										</el-form-item>
								</el-col>
						</el-row>
						<el-row :gutter="24">
								<el-col :span="18" :offset="2">
										<el-form-item label="登录名" prop="code">
												<el-input v-model="metaColumeForm.code"/>
										</el-form-item>
								</el-col>
						</el-row>
						<el-row :gutter="24">
								<el-col :span="18" :offset="2">
										<el-form-item label="密码" prop="password">
												<el-input v-model="metaColumeForm.password"/>
										</el-form-item>
								</el-col>
						</el-row>
                        <el-row :gutter="24">
								<el-col :span="18" :offset="2">
										<el-form-item label="是否管理员" prop="is_admin">
												<el-checkbox v-model="metaColumeForm.is_admin"/>
										</el-form-item>
								</el-col>
						</el-row>
						<div class="form-buttons">
								<el-button @click="reset">重置</el-button>
								<el-button @click="closeDialog">关闭</el-button>
								<el-button type="primary" @click="submitForm">确定</el-button>
						</div>
				</el-form>
		</el-dialog>
        <el-dialog
            title="分配菜单"
            :visible.sync="dialogVisible"
            width="30%">
            <span>选择分配的菜单</span>
            <el-row>
                <el-col>
                    <el-tree
                    ref="tree"
                    :data="userMenu"
                    show-checkbox
                    node-key="id"
                    :default-expanded-keys="['M']"
                    :default-checked-keys="defaultMenu"
                    :props="defaultProps">
                    </el-tree>
                </el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="userMenus">确 定</el-button>
            </span>
        </el-dialog>
	</div>
</template>
<script>
    import ajax from '../../api/ajax/ajax'
    import { mixinParams } from '../../assets/js/mixin1'
    import { VHeader } from '../../components'
    import api from '../../api/url'

    let kanbanAjax = vm => {}

    export default{
        name: 'meta-colume-manager',
        components: {
            VHeader
        },
        mixins: [mixinParams],
        data () {
            return {
                checkList: [],
                dialogVisible: false,
                userMenu: [],
                user_id: '',
                defaultMenu: [],
                defaultProps: {
                    children: 'children',
                    label: 'name'
                },
                options: {
                  colume_attr: [
                    {
                       value: 'default',
                       label: '默认属性'
                    },
                    {
                       value: 'event',
                       label: '事件属性'
                    },
                    {
                      value: 'user',
                      label: '用户属性'
                    },
                    {
                      value: 'equipment',
                      label: '设备属性'
                    }
                  ],
                  data_type: [
                    {
                       value: 'number',
                       label: '数值'
                    },
                    {
                       value: 'date',
                       label: '日期'
                    },
                    {
                      value: 'text',
                      label: '文本'
                    }
                 ]
                },
                tableLoading: true,
                isDownLoadShow: false,
                checked: false,
                condition: '',
                editMode: 'ADD', // 编辑模式
                multipleSelection: [], // 多选数组
                currentPage: 1, // 当前页
                pageSize: 10, // 分页数据条数
                pageTotal: 0, // 总页数
                editDialogShow: false, // 编辑弹窗显示与否
                delMetaColumes: [],
                metaColumeList: [],
                initFormData: {},
                metaColumeForm: {
                    name: '',
                    code: '',
                    password: '',
                    is_admin: ''
                },
                rules: {
                    name: [
                        { required: true, message: '请输入', trigger: 'blur' },
                        { max: 6, message: '最多输入6个字符', trigger: 'blur' }
                    ],
                    code: [
                        { required: true, message: '请输入', trigger: 'blur' },
                        { max: 10, message: '最多输入10个字符', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入', trigger: 'blur' },
                        { max: 16, message: '最多输入16个字符', trigger: 'blur' }
                    ]
                }
            }
        },
        methods: {
            fmtcolumeattr (row, column) {
                return row.colume_attr === 'user' ? '用户属性' : row.colume_attr === 'default' ? '默认属性' : row.colume_attr === 'event' ? '事件属性' : row.colume_attr === 'equipment' ? '设备属性' : '未知属性'
            },
            // 选中表格数据
            handleSelect (selection) {
                if (selection.length > 0) {
                    this.checked = true
										this.metaColumeForm = selection[0]
										this.multipleSelection = selection
                } else {
                    this.checked = false
                }
            },
            handleSelectionChange (selection) {
                this.delMetaColumes = selection.map(item => {
                    return {
                        meta_id: item.meta_id
                    }
                })
            },
            // 分页，每条显示数据
            handleSizeChange (val) {
                this.pageSize = val
                this.handleCurrentChange()
            },
            // 当前页
            handleCurrentChange (val) {
                if (val) {
                    this.currentPage = val
                }
                this.queryUserList()
            },
            // 时间反显格式化
            // setTime (s) {
            //     let dateList = ''
            //     let arr = s.replace(/^(\d{4})(\d{2})(\d{2})$/, '$1,$2,$3').split(',')
            //     dateList = (new Date(new Date().setFullYear(Number(arr[0]), Number(arr[1]) - 1, Number(arr[2]))))
            //     return dateList
            // },
            // 查询列表
            queryUserList () {
							ajax.post(api.QUERY_USERLIST)
								.then(res => {
									this.metaColumeList = res.data.user_list
									this.tableLoading = false
								})
						},
            // 获取日期
            // handleDateChange (val) {
            //     if (val) {
            //         this.te_date = getDateTime(val[0], 's').replace(/^(\d{8})(\d{6})$/, '$1')
            //         this.le_date = getDateTime(val[1], 's').replace(/^(\d{8})(\d{6})$/, '$1')
            //     } else {
            //         this.te_date = ''
            //         this.le_date = ''
            //     }
            // },
            // formatDate () {
            //     // 判断时间是不是对象,要把时间转成string 如 '20180101' 给后台
            //     if (typeof (this.te_date && this.le_date) === 'object') {
            //     let s = getDateTime(this.te_date, 's')
            //     let s1 = getDateTime(this.le_date, 's')
            //     this.te_date = s.substring(0, 8)
            //     this.le_date = s1.substring(0, 8)
            //     }
            // },
            // 新增
            addMetaColume () {
                this.$refs.table.clearSelection()
                this.metaColumeForm = {}
                this.editMode = 'ADD'
                this.editDialogShow = true
                // ajax.post(api.METAIDBUILDER, {meta_table_name: 'meta_colume'}).then((res) => {
                //   this.$set(this.metaColumeForm, 'meta_id', res.data)
								// })
            },
            // 编辑
            modifyMetaColume () {
                // 判断是否可以编辑
                if (this.checked) {
                    if (this.multipleSelection.length < 2) {
                        this.editDialogShow = true
                        this.editMode = 'MODIFY'
                        // 获取时间格式化 再添加到时间选择框里面
                        // let data = this.metaColumeForm
                        // this.te_date = this.setTime(data.te_date)
                        // this.le_date = this.setTime(data.le_date)
                        // this.metaColumeForm.date = [this.te_date, this.le_date]
                        // 定义变量接收一下当前对象
                        this.initFormData = JSON.parse(JSON.stringify(this.metaColumeForm))
                        // 解除双向绑定
                        this.metaColumeForm = JSON.parse(JSON.stringify(this.metaColumeForm))
                    } else {
                        this.$message.error('只能选择一条记录进行编辑')
                    }
                } else {
                    this.$message.error('请选择一条记录进行编辑')
                }
            },
            // 删除
            deleteMetaColume () {
                if (this.checked) {
                    this.$confirm('是否删除所选记录', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        let idList = this.multipleSelection.map(item => item.id)
                        let params = {
                                ids: idList
                        }
                        ajax.post(api.DEL_USER, params).then(res => {
                                this.$message({
                                    type: 'success',
                                    message: '删除成功'
                            })
                            this.queryUserList()
                        })
                    }).catch(() => {})
                } else {
                    this.$message.error('请至少选择一条记录进行删除')
                }
            },
            // 刷新
            refresh () {
                kanbanAjax(this)
                this.queryList()
                this.checked = false
            },
            // 取消新增/编辑
            closeDialog () {
                this.$refs.metaColumeForm.clearValidate()
                this.editDialogShow = false
                this.metaColumeForm = {...this.initFormData}
            },
            // 提交新增/编辑数据
            submitForm () {
                this.$refs.metaColumeForm.validate(valid => {
                    // this.formatDate()
                    if (valid) {
                        let params = {
                            name: this.metaColumeForm.name,
                            code: this.metaColumeForm.code,
                            password: this.metaColumeForm.password,
                            is_admin: this.metaColumeForm.is_admin === true ? '1' : '0'
                        }
                        if (this.editMode === 'ADD') {
                            // 新增
                            ajax.post(api.ADD_USER, params)
                                .then(res => {
                                    this.$message({
                                        type: 'success',
                                        message: '增加成功'
                                    })
                                    this.queryUserList()
                                    this.editDialogShow = false
                                })
                        } else if (this.editMode === 'MODIFY') {
                            // 修改接口
                            let insertData = 1 // 自己随便写的
                            ajax.post(api.UPDATE_METACOLUME, insertData).then((res) => {
                                this.ruleForm = {}
                                this.handleSizeChange()
                            })
                            .then(() => {
                                this.$message({
                                    type: 'success',
                                    message: '编辑成功!'
                                })
                            })
                            .catch(() => {
                                this.$message({
                                    type: 'info',
                                    message: '已取消添加'
                                })
                            })
                            this.editDialogShow = false
                            this.refresh()
                        } else {
                            return false
                        }
                    }
                })
            },
            // 条件查询
            conditionquery () {
                const conditiondata = {
                    keyword: this.condition
                }
                ajax.post(api.SELECT_METACOLUME_LIST_FOR_PAGE, conditiondata).then((res) => {
                    this.metaColumeList = res.data.list
                    this.pageTotal = res.data.total
                })
            },
            // 重置表单
            reset () {
                if (this.editMode === 'ADD') {
                    this.metaColumeForm = {}
                } else if (this.editMode === 'MODIFY') {
                    this.metaColumeForm = {...this.initFormData}
                }
                this.$refs.metaColumeForm.clearValidate()
            },
            // 分配操作
            handleClick (v) {
                this.dialogVisible = true
                this.user_id = v.id
                let params = {
                    user_id: v.id
                }
                ajax.post(api.USER_MENU, params)
                    .then(res => {
                        this.userMenu = res.data.all_menus
                        this.defaultMenu = res.data.has_menus
                        this.defaultMenu = this.defaultMenu.filter(item => item !== 'M')
                    })
            },
            userMenus () {
                let idlist = this.$refs.tree.getCheckedKeys()
                if (idlist.length === 0) {
                    this.$message({
                        type: 'error',
                        message: '至少分配一个'
                    })
                } else {
                    let params = {
                        user_id: this.user_id,
                        ids: this.$refs.tree.getCheckedKeys().push('M')
                    }
                    ajax.post(api.ASSIGN_USER, params)
                        .then(res => {
                            this.$message({
                                type: 'success',
                                message: '分配成功'
                            })
                            this.dialogVisible = false
                        })
                }
            }
        },
        created () {
            this.queryUserList()
        },
        mounted () {
            // this.queryUserMenu()
        }
    }
</script>
<style lang="stylus" rel="stylesheet/stylus">
#metaColumeManager
    height 100%
    .meta-colume-box
        overflow auto
        height calc(100% - 56px)
        margin 10px 0 0 10px
        padding-right 10px
    .header-tool-bar
        padding 0 20px
        background #fff
        line-height 50px
        .conditionquery
            width 300px
            float right
            margin-right -10px
            .el-input--mini
                width 200px
            .el-button
               vertical-align middle
    .main-cont
        padding 0
        margin-top 3px
        background #fff
        .el-pagination
          padding 10px 15px 10px 0
          line-height 30px
          text-align right
    .el-dialog
        width 600px
        .el-dialog__body
            padding 30px
    .el-form
        .el-input
            .el-input__inner
                height 40px
        .el-date-editor
            width 100%!important
            height 40px
            .el-range-separator
                vertical-align top
                height 40px
                line-height 40px
        .el-select
          width 268px
          height 40px
        .form-buttons
            text-align right
</style>
